package num38;

/**
 * 38. 外观数列
 *
 * 题目：https://leetcode-cn.com/problems/count-and-say/
 * 三叶姐题解: https://leetcode-cn.com/problems/count-and-say/solution/shua-chuan-lc-100-mo-ni-ti-shi-yong-shao-w8jl/
 *
 * 自己做的
 */
class Solution {
    public String countAndSay(int n) {
        if (n <= 1) {
            return "1";
        }
        String res = "11";


        for (int i = 2; i < n; i++) {
            StringBuilder sb = new StringBuilder();
            int count = 1;
            int length = res.length();
            for (int j = 1; j < length; j++) {
                // 获取字符相同的个数
                if (res.charAt(j) == res.charAt(j - 1)) {
                    count++;
                } else {
                    // 对于每个组，先描述字符的数量，然后描述字符，形成一个描述组
                    sb.append(count);
                    sb.append(res.charAt(j - 1));

                    // 重置
                    count = 1;
                }
                // 最终
                if (j == res.length() - 1) {
                    sb.append(count);
                    sb.append(res.charAt(j));
                    res = sb.toString();

                    // 清空
                    sb.delete(0, sb.length());
                }

            }
        }
        return res;
    }


    public static void main(String[] args) {
        System.out.println(new Solution().countAndSay(4));

    }
}